package com.wtgroup.demo.mianshi.容器.链表;

/**
 * 数组实现队列
 *
 * @author dafei
 * @version 0.1
 * @date 2021/4/16 17:18
 */
public class D4_数组队列 {
    public static void main(String[] args) {
        ArrayQueue arrayQueue = new ArrayQueue();
        for (int i = 0; i < 10; i++) {
            arrayQueue.push(i);
        }
        for (int i = 0; i < 10; i++) {
            Object pop = arrayQueue.pop();
            System.out.println(pop);
        }
    }


    public static class ArrayQueue {
        private int cap = 10;
        private Object[] tab = new Object[cap];
        // push值到此位置
        private int pushOffset = 0;
        // 弹出偏移量, 弹出时取此位置值
        private int popOffset = 0;
        private int size = 0;

        public void push(Object val) {
            if (size==cap) {
                throw new RuntimeException("满了");
            }

            tab[pushOffset] = val;
            size++;
            pushOffset = offset(pushOffset);
        }

        public Object pop() {
            if (size==0) {
                throw new RuntimeException("空了");
            }
            Object ret = tab[popOffset];
            popOffset = offset(popOffset);
            size--;
            return ret;
        }

        // 偏移量移动, 越界了, 回到0
        private int offset(int ot) {
            return ot < cap - 1 ? ot+1 : 0;
        }
    }


}
